<?php

namespace App\Http\Controllers\Member;

use App\Ext\SMS\ChuanglanService;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Model\Member;

/**
 * Class GuestController
 * @package App\Http\Controllers\Member
 */
class GuestController extends Controller
{
    /**
     * 登录接口
     *
     * @param Request $request
     * @return array
     */
    public function login(Request $request){
        $rules = array(
            'password' => 'required|alpha_num|between:6,32',
            'mobile'=>'regex:/^1[34578][0-9]{9}$/',
//            'email' => 'email',
        );
        $message = array(
            "required"             => ":attribute 不能为空",
            "between"      => ":attribute 长度必须在 :min 和 :max 之间",
//            "email"      => ":attribute 格式不正确",
            "alpha_num"      => ":attribute 不能使用字母数字之外的字符",
            "regex"      => "非法手机号"
        );

        $attributes = array(
            "password" => '密码',
            'mobile' => "手机号",
//            'email' => '邮箱',
        );

        $validate = Validator::make($request->all(),$rules,$message,$attributes);
        if($validate->fails()){
            $warnings = $validate->messages();
            $show_warning = $warnings->first();
//            return $warnings;
            return $this->error(1, $warnings.$show_warning);
        }
        $mobile = $request->input('mobile'); //123
//        $email = $request->input('email'); //123@qq.com
        $password = $request->input('password'); //123123
//        $member = new Member;
//        if ($mobile) $obj = $member->where('mobile', $mobile);
//        if ($email) $obj = $obj->where('email', $email);
        $member= Member::where('mobile', $mobile)->first();
        if(!$member){
            return $this->error(2, 'No found this account');
        }
        if($member->password == '' || $member->status == 0) {
            return $this->error(3, 'The account is unenable.');
        }
        if (!Hash::check($password, $member->password)) {
            return $this->error(4, 'Password is error!');
        }
        $respone = [
            'member_id' => $member->id,
            'mobile' => $member->mobile,
            'username' => $member->username
        ];
        return $this->success($respone);
    }

    /**
     * 注册新用户
     *
     * @param Request $request
     * @return array
     */
    public function register(Request $request) {
        $rules = array(
            'mobile'=>'required|regex:/^1[34578][0-9]{9}$/',
            'email' => 'required|email',
            'password' => 'required|alpha_num|between:6,32|confirmed',
            'password_confirmation' => 'required',
            'code' => 'required',
        );
        $message = array(
            "required"             => ":attribute 不能为空",
            "between"      => ":attribute 长度必须在 :min 和 :max 之间",
            "email"      => ":attribute 格式不正确",
            "alpha_num"      => ":attribute 不能使用字母数字之外的字符",
            "regex"      => "非法手机号",
            "confirmed"      => "两次输入的密码不一样"
        );

        $attributes = array(
            "password" => '密码',
            'mobile' => "手机号",
            'email' => '邮箱',
            'code' => '验证码',
        );

        $validate = Validator::make($request->all(),$rules,$message,$attributes);
        if($validate->fails()){
            $warnings = $validate->messages();
            $show_warning = $warnings->first();
//            return $warnings.$show_warning;
            return $this->error(1, $warnings.$show_warning);
        }
        $mobile = $request->input('mobile');
        $email = $request->input('email');
        $code = $request->input('code');
//        $vCode = Session::get('vcode');
        $password = $request->input('password');
        $passwordConfirmation = $request->input('password_confirmation');
//        if($code != $vCode){
//            return json_encode(array('error' => 2, 'msg' => 'code error'));
//        }
//        $list = Member::insert([
//            'mobile'=>$mobile,
//            'email'=>$email,
//            'password'=>Hash::make($password),
//        ]);
        $member = Member::where('mobile', $mobile)->first();
        if(!$member){
            return $this->error(1, 'Register fail, pleas gain the code for mobile message!');
        }
        if($member->password != ''){
            return $this->error(2, 'The account has been registered!');
        }
        if($member->code != $code){
            return $this->error(3, 'The code is error！');
        }
        if ($member->code_time < time()) {
            return $this->error(4, 'Message Captcha is over time, please send again.');
        }
        if($password != $passwordConfirmation) {
            return $this->error(5, 'Two passwords are inconsistent.');
        }
        $member->password = Hash::make($password);
        $member->email = $email;
        $member->status = 1;
        if($member->save()){
            return $this->success();
        }else{
//            return json_encode(array('error' => 1, 'msg' => 'error'));
            return $this->error(6, 'Register fail!!');
        }

    }
    /**
     *短信验证码找回密码
     *
     * @param Request $request
     * @return array
     */
    public function forgot(Request $request) {

        if (!$request->has('mobile')) {
            return $this->error(1,'参数错误');
        }
        $mobile = $request->input('mobile');
//        if(!$this->regex('mobile', $mobile)) {
////            return $this->error(2, '手机格式有误');
//        }
        if (!$request->has('password')) {
            return $this->error(3,'参数错误');
        }
        $password = $request->input('password');
        if (empty($password)) {
            return $this->error(4,'密码不能为空');
        }
        if (!$request->has('password_confirmation')) {
            return $this->error(5,'参数错误');
        }
        $passwordAgain = $request->input('password_confirmation');
        if (empty($password)) {
            return $this->error(6,'确认密码不能为空');
        }
        if($password != $passwordAgain) {
            return $this->error(7,'两次密码不一致');
        }
        if (!$request->has('code')) {
            return $this->error(8,'短信验证码不能为空');
        }
        $code = $request->input('code');
        # 检查短信验证码是否正确
        $member = Member::where('mobile', $mobile)->where('code', $code)->first();
        if (!$member) {
            return $this->error(9,'短信验证码不正确');
        }
        if ($member->code_time < time()) {
            return $this->error(10,'短信验证码已过期，请重新发送！');
        }
        # 修改用户密码

        $member->password = Hash::make($password);
        $member->ip = $request->ip();
        if ($member->save()) {
            return $this->success();
        }
        return $this->error(11,'修改失败');
    }

    /**
     * 发送注册短信验证码
     *
     * @param Request $request
     * @return array
     */
    public function registerPhone(Request $request) {
        if (!$request->has('mobile')) {
            return $this->error(1,'参数错误');
        }
        $mobile = $request->input('mobile');
//        if(!$this->regex('mobile', $mobile)) {
////            return $this->error(2, '手机格式有误');
//        }

        # 检查手机号是否已注册
        $member = Member::where('mobile', $mobile)->first();
        if ($member) {
            if (!empty($member->password)) {
                return $this->error(3,'该手机号已经注册');
            }
        } else {
            # 手机号不存在，插入新记录
            $member = new Member();
            $member->mobile = $mobile;
        }
        # 生成code并更新到数据库
        $code = randNumber(4);
        $member->code = $code;
        $member->code_time = time() + (2 * 3600);
        if ($member->save()) {
            # 发送短信验证码
            $sms = new ChuanglanService('I2598663','GaX6j1gtwIa534',2);
            $msg = '【Steam】您好，您的验证码：' . $code . '。2小时内有效';
            $result = $sms->sendInternational(86 . $mobile, $msg);
            $result = json_decode($result, true);
            if (!empty($result) && $result['success']) {
                $response['data'] = $result;
                $response['message'] = $msg;
                return $this->success($response);
            }
            return $this->error(4, '短信验证失败', $result);
        }
        return $this->error(5,'生成短信验证码错误');

    }

    /**
     * 发送找回密码短信验证码
     *
     * @param Request $request
     * @return array
     */
    public function forgotPhone(Request $request) {
        if (!$request->has('mobile')) {
            return $this->error(1, '参数错误');
        }
        $mobile = $request->input('mobile');
//        if(!$this->regex('mobile', $mobile)) {
////            return $this->error(2, '手机格式有误');
//        }
        # 检查手机号是否已注册
        $member = Member::where('mobile', $mobile)->first();
        if (!$member) {
            return $this->error(3, '用户不存在');
        }
        # 生成code并更新到数据库
        $code = randNumber(4);
        $member->code = $code;
        $member->code_time = time() + (2 * 3600);
        if ($member->save()) {
            # 发送短信验证码
            $sms = new ChuanglanService('I2598663', 'GaX6j1gtwIa534', 2);
            $msg = '【Steam】您好，您的验证码：' . $code . '。2小时内有效';
            $result = $sms->sendInternational(86 . $mobile, $msg);
            $result = json_decode($result, true);
            if (!empty($result) && $result['success']) {
                $response['data'] = $result;
                $response['message'] = $msg;
                return $this->success($response);
            }
            return $this->error(4, '短信验证失败', $result);
        }
        return $this->error(5, '生成短信验证码错误');
    }

    /**
     * 发送找回密码验证邮件
     *
     * @param Request $request
     * @return array
     */
    public function forgotEmail(Request $request) {
        $email = $request->input('email');
        return $this->success();
    }
}